'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.default = createOne;

var _helpers = require('./helpers');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createOne(model, tc, opts) {
  if (!model || !model.modelName || !model.schema) {
    throw new Error('First arg for Resolver createOne() should be instance of Mongoose Model.');
  }

  if (!tc || tc.constructor.name !== 'TypeComposer') {
    throw new Error('Second arg for Resolver createOne() should be instance of TypeComposer.');
  }

  const outputTypeName = `CreateOne${tc.getTypeName()}Payload`;
  const outputType = tc.constructor.schemaComposer.getOrCreateTC(outputTypeName, t => {
    t.addFields({
      recordId: {
        type: 'MongoID',
        description: 'Created document ID'
      },
      record: {
        type: tc,
        description: 'Created document'
      }
    });
  });

  const resolver = new tc.constructor.schemaComposer.Resolver({
    name: 'createOne',
    kind: 'mutation',
    description: 'Create one document with mongoose defaults, setters, hooks and validation',
    type: outputType,
    args: (0, _extends3.default)({}, (0, _helpers.recordHelperArgs)(tc, (0, _extends3.default)({
      recordTypeName: `CreateOne${tc.getTypeName()}Input`,
      removeFields: ['id', '_id'],
      isRequired: true
    }, opts && opts.record))),
    resolve: (() => {
      var _ref = (0, _asyncToGenerator3.default)(function* (resolveParams) {
        const recordData = resolveParams.args && resolveParams.args.record || {};

        if (!(typeof recordData === 'object') || Object.keys(recordData).length === 0) {
          throw new Error(`${tc.getTypeName()}.createOne resolver requires at least one value in args.record`);
        }

        let doc = new model(recordData);
        if (resolveParams.beforeRecordMutate) {
          doc = yield resolveParams.beforeRecordMutate(doc, resolveParams);
          if (!doc) return null;
        }
        yield doc.save();

        return {
          record: doc,
          recordId: tc.getRecordIdFn()(doc)
        };
      });

      return function resolve(_x) {
        return _ref.apply(this, arguments);
      };
    })()
  });

  return resolver;
}
/* eslint-disable no-param-reassign, new-cap */